# -*- coding: utf-8 -*-
import time
import os, sys, pdb, re, hashlib
from natsort import natsorted
import argparse
import traceback

DEFAULT_TYPE = "bmp,jpg,png,tif,gif,pcx,tga,exif,fpx,svg,psd,cdr,pcd,JPEG,dxf,ufo,eps,ai,raw,WMF,webp"


def printMy(*objects, sep=' ', end='\n', file=sys.stdout, flush=False):
    nowDateTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    objects = [nowDateTime, *objects]
    print(*objects, sep=sep, end=end, file=file, flush=flush)
    try:
        print(*objects, sep=sep, end=end, file=open("./log.log", 'a'), flush=flush)
    except BaseException as e:
        print(traceback.format_exc())
        pass


def getFileHash(file):
    """
    获取文件的hash (md5,性能太差,直接返回文件名)
    """
    # m = hashlib.md5()
    # with open(file, 'rb') as f:
    #     for line in f:
    #         m.update(line)
    # md5code = m.hexdigest()
    # return md5code
    return file


def wFile(file, text, append='a'):
    with open("./" + file, append, encoding='utf-8') as f:
        f.write(text)


# pip install beautifulsoup4
# pdb.set_trace()
def isMatch(nowStr, matchs):
    """
        判断nowStr是否部分匹配matchs中任意一个
    """
    for nowEx in matchs:
        if (nowStr.find(nowEx) != -1):
            return True
    return False


def filterFileFun(fileName, *suffix):
    try:
        for nowSuffix in suffix:
            if fileName.endswith("." + nowSuffix) or fileName.endswith("." + nowSuffix.swapcase()):
                return True
    except BaseException as e:
        printMy(traceback.format_exc(e))
    return False


def getInitListFileStr(nowFile=""):
    return '''DAUMPLAYLIST
playname={0}
topindex=0
saveplaypos=0
'''.format(nowFile)


def initListFile(listFile, nowFile):
    wFile(listFile, getInitListFileStr(nowFile), 'w')


def main():
    """
    Run autosub as a command-line program.
    """
    parser = argparse.ArgumentParser()
    parser.add_argument('source_path', help="Path default .",
                        nargs='?', default=".")
    parser.add_argument('-N', '--name', help="name default: list", default="list")
    parser.add_argument('-T', '--type',
                        help="type default: 'bmp,jpg,png,tif,gif,pcx,tga,exif,fpx,svg,psd,cdr,pcd,JPEG,dxf,ufo,eps,ai,raw,WMF,webp'",
                        type=str, default=DEFAULT_TYPE)
    parser.add_argument('-M', '--match', help="match default: None",
                        type=str, default=None)
    parser.add_argument('-NM', '--notMatch', help="not match default: None",
                        type=str, default=None)
    parser.add_argument('-MN', '--maxNum', help="maxNum default: None",
                        type=int, default=None)
    parser.add_argument('-MinS', '--minSize', help="min file size unit B default: 0",
                        type=int, default=0)
    args = parser.parse_args()

    try:
        sourcePath = args.source_path.split(',')
        types = args.type.split(',')
        match = args.match
        minSize = args.minSize
        if match is not None:
            match = match.split(',')
        # 反向匹配,筛选不匹配的
        notMatch = args.notMatch
        if notMatch is not None:
            notMatch = notMatch.split(',')
        name = args.name
        maxNum = args.maxNum
        nowListFile = readListFile = name + ".dpl"
        # 当前文件的index,从1开始
        nowIndex = 1
        # 下一个列表文件的index,根据maxNum自动分
        nextListFileIndex = readNextListFileIndex = 1
        # 当前列表已经存在的文件
        existsFiles = []
        # pdb.set_trace()
        # 上一个文件是否匹配
        isPrevFileExists = True
        # 需要写入到新文件的文件列表字符串, 下标为新文件的index,从0开始
        newListFileStr = {0: ""}
        # 读取到老文件的头信息,下标为读取文件的index,从0开始
        readListFileStart = {}
        # 如果文件存在，读取，过滤清理已经删除的文件
        while (True):
            if not os.path.exists(readListFile):
                break
            with open(readListFile, 'r', encoding='utf-8') as f:
                # 是否已经匹配到文件行
                isMatchFileIng = False
                readListFileStart[readNextListFileIndex - 1] = ""
                for nowLine in f.readlines():
                    # nowLine = f.readline()
                    # if not nowLine:
                    #     break
                    # 匹配项目 3*file*E:\YOKA\project\potplayer_playlist_generator\460.gif
                    # matchFile = re.match(r'^(\d+)\*file\*(.*)$', nowLine)
                    matchFile = re.match(r'^(.+)\*file\*(.*)$', nowLine)
                    # 匹配到文件行
                    if matchFile:
                        isMatchFileIng = True
                        nowFilePath = matchFile.group(2)
                        if os.path.exists(nowFilePath) and os.path.getsize(nowFilePath) > minSize:
                            isPrevFileExists = True
                            # 正向匹配支持
                            if match is not None:
                                if not isMatch(nowFilePath, match):
                                    isPrevFileExists = False
                                    continue
                            # 反向匹配支持
                            if notMatch is not None:
                                if isMatch(nowFilePath, notMatch):
                                    isPrevFileExists = False
                                    continue
                            nowFileMd5 = getFileHash(nowFilePath)
                            if nowFileMd5 in existsFiles:
                                isPrevFileExists = False
                                continue
                            # 超过最大大小, 新建列表文件
                            if maxNum is not None and nowIndex > maxNum:
                                # 终结上一个文件
                                # 开始新文件流程
                                # newListFileStr[nextListFileIndex] = getInitListFileStr(nowFilePath)
                                newListFileStr[nextListFileIndex] = ""
                                nowIndex = 1
                                nowListFile = name + str(nextListFileIndex) + ".dpl"
                                nextListFileIndex = nextListFileIndex + 1
                            # 替换index
                            nowLine = re.sub(r'^\d+', str(nowIndex), nowLine, 1)
                            # 写入新文件行
                            newListFileStr[nextListFileIndex - 1] = newListFileStr[nextListFileIndex - 1] + nowLine
                            nowIndex = nowIndex + 1
                            existsFiles.append(nowFileMd5)
                        else:
                            isPrevFileExists = False
                            continue
                    else:
                        # 还没匹配到文件的是初始内容
                        if not isMatchFileIng:
                            readListFileStart[readNextListFileIndex - 1] = readListFileStart[
                                                                               readNextListFileIndex - 1] + nowLine
                        else:
                            # 没有匹配文件行,上一个文件存在才写入新文件行
                            if isPrevFileExists:
                                nowLine = re.sub(r'^\d+', str(nowIndex - 1), nowLine, 1)
                                newListFileStr[nextListFileIndex - 1] = newListFileStr[nextListFileIndex - 1] + nowLine
            # 删除读取完的文件
            os.remove(readListFile)
            readListFile = name + str(readNextListFileIndex) + ".dpl"
            readNextListFileIndex = readNextListFileIndex + 1
        # 写入整理完之后的文件列表
        for (listFileIndex, listFileStr) in newListFileStr.items():
            if listFileStr == "":
                continue
            # 确定列表文件名
            if listFileIndex == 0:
                nowListFilePath = name + ".dpl"
            else:
                nowListFilePath = name + str(listFileIndex) + ".dpl"
            # 确定列表文件头部
            if listFileIndex in readListFileStart.keys():
                listFileStr = readListFileStart[listFileIndex] + listFileStr
            else:
                listFileStr = getInitListFileStr() + listFileStr
            wFile(nowListFilePath, listFileStr, 'w')
        # 新的文件内容
        newListFileStr = ""
        for nowPath in sourcePath:
            if nowPath == ".":
                nowPath = os.getcwd()
            for maindir, subdir, file_name_list in os.walk(nowPath):
                # print("1:",maindir) #当前主目录
                # print("2:",subdir) #当前主目录下的所有目录
                # print("3:",file_name_list)  #当前主目录下的所有文件
                # file_name_list.sort()
                file_name_list = natsorted(file_name_list)
                for nowFile in file_name_list:
                    if filterFileFun(nowFile, *types) and os.path.getsize(maindir + "\\" + nowFile) > minSize:
                        nowFile = maindir + "\\" + nowFile
                        # 正向匹配支持
                        if match is not None:
                            if not isMatch(nowFile, match):
                                continue
                        # 反向匹配支持
                        if notMatch is not None:
                            if isMatch(nowFile, notMatch):
                                continue
                        # 文件md5比较,存在的不重复添加
                        nowFileMd5 = getFileHash(nowFile)
                        if nowFileMd5 in existsFiles:
                            continue
                        existsFiles.append(nowFileMd5)
                        # 初始化列表
                        if nowIndex == 1:
                            newListFileStr = getInitListFileStr(nowFile)
                        # 超过最大大小, 新建列表文件
                        if maxNum is not None and nowIndex > maxNum:
                            # 开始新文件流程
                            nowIndex = 1
                            # 把之前的写进去
                            if os.path.exists(nowListFile):
                                wFile(nowListFile, newListFileStr, 'a')
                            else:
                                wFile(nowListFile, newListFileStr, 'w')

                            nowListFile = name + str(nextListFileIndex) + ".dpl"
                            nextListFileIndex = nextListFileIndex + 1
                            # 复位
                            newListFileStr = getInitListFileStr(nowFile)
#                         nowCon = '''{0}*file*{1}
# {0}*played*0
# '''.format(nowIndex, nowFile)
                        nowCon = '''{0}*file*{1}
'''.format(nowIndex, nowFile)
                        newListFileStr = newListFileStr + nowCon
                        nowIndex = nowIndex + 1
        wFile(nowListFile, newListFileStr, 'a')
        printMy("%s lastFile: %s sum: %s" % (sourcePath, nowListFile, ((maxNum * (nextListFileIndex-1)) + (nowIndex - 1)) if maxNum is not None else (nowIndex - 1)))
    except BaseException as e:
        printMy(traceback.format_exc())
        return 1

    return 0


if __name__ == '__main__':
    sys.exit(main())
